<?php
/**
 * ai自动生成文章的标题和内容
 */

namespace App\Console\Commands;

use App\Common\Ai\XFYunApi;
use App\Common\Logs\Logs;
use App\Common\Utill\Utills;
use App\Models\Articles;
use App\Models\Category;
use App\Models\Tasks;
use App\Models\TasksRecord;
use App\Service\ArticlesService;
use App\Service\WebsitesService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CreateArticle extends Command
{
    /**
     * CreateArticle {param1?} {param2?}
     * The name and signature of the console command.
     * @var string
     */
    protected $signature = 'CreateArticle';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'ai自动生成文章的标题和内容';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        //接收参数
        //$param1 = $this->argument('param1'); // 不指定参数名的情况下用argument
        $taskSn = date('ymdHis') . rand(10, 99);
        $beginTime = time();
        $this->taskDataNobegin();
        //获取进行中的任务
        $taskData = Tasks::query()
            ->where('status',1)
            ->where('is_del',1)
            ->select('id','websites_id','websites_topic_id','plan_numbers','finish_numbers')->first();
        if(!$taskData){
            Logs::crontabLog('无进行中的任务',[],'task');
            return  false;
        }
        $taskId = $taskData['id'];
        $planNumber    = $taskData['plan_numbers'];
        $finishNumber  = $taskData['finish_numbers'];
        $websitesId    = $taskData['websites_id'];
        $topicsId      = $taskData['websites_topic_id'];
        $taskInfo = "任务id:".$taskId.',订单号:'.$taskSn;
        //标题信息
        $articleTitleArr = $this->articleTitle($taskInfo,$websitesId,$taskSn);
        if(!$articleTitleArr){
            Logs::crontabLog($taskInfo.",无关键词,终止生成标题",[],'task');
            return  false;
        }
        $category_ids = $articleTitleArr['title_ids'];
        $title = $articleTitleArr['title'];
        $weights = $articleTitleArr['weights'];
        //内容信息
        $articleContentArr = $this->articleContent($title,$taskSn);
        $content = $articleContentArr['content'];
        $thumbs = $articleContentArr['thumbs'];
        $server = new ArticlesService();
        $articleId = $server->store($category_ids, $websitesId,$topicsId, $title, $content, $thumbs, 2);
        if($articleId){
            //任务统计
            $saveTask['finish_numbers'] = $finishNumber + 1;
            if($saveTask['finish_numbers'] >= $planNumber){
                $saveTask['status'] = 2;
            }
            Tasks::query()->where('id',$taskId)->update($saveTask);
            //任务统计记录表
            $taskRecord['task_id'] = $taskId;
            $taskRecord['article_id'] = $articleId;
            $taskRecord['created_at'] = date('Y-m-d H:i:s');
            TasksRecord::query()->insert($taskRecord);
            //更新权重
            if($weights){
                DB::table("pd_category")->where("id",$category_ids)->update(['weights'=>0]);
            }
        }
        echo "success:" . date("Y-m-d H:i:s") . "\n";
        $endTime = time();
        $totalTime = $endTime - $beginTime;
        Logs::crontabLog('执行id:' . $taskSn . ',生成文章id:' . $articleId . ',开始时间:' . date("Y-m-d H:i:s", $beginTime) . ",结束时间:" . date("Y-m-d H:i:s", $endTime) . ',总计:' . $totalTime . "秒",[],'task');
        return false;
    }

    /**
     * 任务待开始 =》 进行中
     * @return void
     */
    public function taskDataNobegin()
    {
        $beginTime = time();
        $taskData = Tasks::query()
            ->where('status',0)
            ->where('is_del',1)
            ->where('plan_time','<=',$beginTime)
            ->select('id')
            ->get()
            ->toArray();
        if($taskData){
             $whereIni = array_column($taskData,'id');
             Tasks::query()->whereIn('id',$whereIni)->update(['status'=>1]);
        }
    }

    /**
     * 生成文章的标题
     * @return mixed|string|null
     */
    public function articleTitle($taskInfo,$websitesId,$taskSn)
    {
        $result = [];
        //编号
        $orderSn = Utills::aiOrderSn();
        //分类信息
        $categoryData = $this->categoryData($websitesId);
        if(!$categoryData){
           return  $result;
        }
        $result['title_ids'] = $categoryData['id'];
        $result['weights'] = $categoryData['weights'];
        //关键字
        $articleTitle = $categoryData['category_name'];
        $serverObj = new ArticlesService();
        //整合关键字
        $getTitleText = $serverObj->getTitleText($articleTitle);
        //发送
        $xfYunApi = new XFYunApi();
        $aiResult = $xfYunApi->sendRequest($orderSn, $getTitleText);
        //处理结果
        $returnContent = $serverObj->articlesTokenRecord(1, $orderSn, $getTitleText, $aiResult, 2,$taskSn);
        Logs::crontabLog($taskInfo.",step-1 关键词id:".$result['title_ids'].",关键词名称:".$articleTitle.",标题号:{$orderSn},生成标题:".$returnContent['content'],[],'task');
        $result['title'] = $returnContent['content'];
        return $result;
    }

    /**
     * 生成文章的内容
     * @return mixed|string|null
     */
    public function articleContent($articleKeyword,$taskSn)
    {
        $result = [];
        $orderSn = Utills::aiOrderSn();
        $serverObj2 = new ArticlesService();
        //整合关键字
        $getContentText = $serverObj2->getContentText($articleKeyword);
        //发送
        $xfYunApi2 = new XFYunApi();
        $aiResult = $xfYunApi2->sendRequest($orderSn, $getContentText, 2);
        //处理结果
        $returnContent2 = $serverObj2->articlesTokenRecord(2, $orderSn, $getContentText, $aiResult, 2,$taskSn);
//        Log::info("执行id:{$orderSn},ai生成文章step-4 结果: ".$returnContent2['content']);
        $result['content'] = $returnContent2['content'];
        $result['thumbs'] = $returnContent2['thumbs'];
        return $result;
    }

    /**
     * 获取分类的名称
     * @param  //$websitesId 网站id
     * @return array
     */
    public function categoryData($websitesId)
    {
        $teshuCategory = Category::query()
            ->where('website_id',1)
            ->where("is_del", 1)
            ->where("weights",">",0)
            ->select("id", "category_name","weights")
            ->first();
        if($teshuCategory){
            $result['id'] = $teshuCategory['id'];
            $result['category_name'] = $teshuCategory['category_name'];
            $result['weights'] = $teshuCategory['weights'];
            return  $result;
        }
        $data = DB::table("pd_category")
            ->where('website_id',1)
            ->where("is_del", 1)
            ->inRandomOrder()
            ->limit(3)
            ->select("id", "category_name")
            ->get()
            ->toArray();
        if(!$data){
            return  [];
        }
        $newData = [];
        foreach ($data as $kk => $vv) {
            $newData[$vv->id] = $vv->category_name;
        }
        $newDataKey = array_keys($newData);
        shuffle($newDataKey);
        $result['id'] = $newDataKey[0];
        $result['category_name'] = $newData[$newDataKey[0]];
        $result['weights'] = 0;
        return $result;
    }
}
